import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QMessageBox, QStackedWidget,
                             QGroupBox, QFormLayout, QDialog, QTabWidget, QTableWidget,
                             QTableWidgetItem, QHeaderView, QComboBox, QTextEdit, QGridLayout,
                             QSpinBox, QRadioButton, QButtonGroup)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
from iteration4_maintenance_management.report_maintenance import MaintenanceReporter
from iteration4_maintenance_management.query_maintenance import MaintenanceQuery
from iteration4_maintenance_management.update_maintenance import MaintenanceUpdater

# 宿舍报修窗口
class ReportMaintenanceDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('宿舍报修')
        self.setGeometry(300, 300, 400, 300)
        self.reporter = MaintenanceReporter()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 获取所有宿舍信息
        db = Database()
        db.connect()
        db.cursor.execute(
            "SELECT id, building, room_number FROM dormitory ORDER BY building, room_number"
        )
        dormitories = db.cursor.fetchall()
        db.close()
        
        # 宿舍选择下拉框
        self.dormitory_combo = QComboBox()
        for dorm in dormitories:
            self.dormitory_combo.addItem(f"{dorm[1]}-{dorm[2]} (ID: {dorm[0]})", dorm[0])
        form_layout.addRow('宿舍:', self.dormitory_combo)
        
        # 问题描述文本框
        self.issue_input = QTextEdit()
        self.issue_input.setPlaceholderText('请描述问题...')
        form_layout.addRow('问题描述:', self.issue_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('报修信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.report_button = QPushButton('报修')
        self.report_button.clicked.connect(self.report_maintenance)
        button_layout.addWidget(self.report_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def report_maintenance(self):
        dormitory_id = self.dormitory_combo.currentData()
        issue_description = self.issue_input.toPlainText().strip()
        
        if not issue_description:
            QMessageBox.warning(self, '警告', '问题描述不能为空')
            return
        
        result = self.reporter.report_maintenance(dormitory_id, issue_description)
        
        if result:
            QMessageBox.information(self, '成功', '宿舍报修信息已提交')
            self.accept()

# 维修记录查询窗口
class QueryMaintenanceWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.query = MaintenanceQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询选项
        option_group = QGroupBox('查询选项')
        option_layout = QVBoxLayout()
        
        self.query_all_btn = QRadioButton('查询所有维修记录')
        self.query_all_btn.setChecked(True)
        option_layout.addWidget(self.query_all_btn)
        
        self.query_by_dormitory_btn = QRadioButton('根据宿舍查询维修记录')
        option_layout.addWidget(self.query_by_dormitory_btn)
        
        self.query_by_status_btn = QRadioButton('根据维修状态查询记录')
        option_layout.addWidget(self.query_by_status_btn)
        
        # 创建按钮组
        self.query_button_group = QButtonGroup()
        self.query_button_group.addButton(self.query_all_btn, 1)
        self.query_button_group.addButton(self.query_by_dormitory_btn, 2)
        self.query_button_group.addButton(self.query_by_status_btn, 3)
        
        option_group.setLayout(option_layout)
        layout.addWidget(option_group)
        
        # 查询参数表单
        self.param_group = QGroupBox('查询参数')
        self.param_layout = QFormLayout()
        
        self.dormitory_id_input = QLineEdit()
        self.dormitory_id_input.setPlaceholderText('例如: 1')
        self.param_layout.addRow('宿舍ID:', self.dormitory_id_input)
        
        self.status_combo = QComboBox()
        self.status_combo.addItem('待处理', 'pending')
        self.status_combo.addItem('处理中', 'in_progress')
        self.status_combo.addItem('已完成', 'completed')
        self.param_layout.addRow('维修状态:', self.status_combo)
        
        self.param_group.setLayout(self.param_layout)
        self.param_group.setVisible(False)
        layout.addWidget(self.param_group)
        
        # 查询按钮
        self.query_btn = QPushButton('查询')
        self.query_btn.clicked.connect(self.perform_query)
        layout.addWidget(self.query_btn)
        
        # 结果表格
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(6)
        self.result_table.setHorizontalHeaderLabels(['记录ID', '宿舍', '问题描述', '报修时间', '状态', '解决时间'])
        self.result_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.result_table)
        
        # 连接信号
        self.query_button_group.buttonClicked.connect(self.on_query_option_changed)
        
        self.setLayout(layout)
    
    def on_query_option_changed(self, button):
        # 隐藏所有输入框
        for i in range(self.param_layout.rowCount()):
            self.param_layout.itemAt(i * 2 + 1).widget().setVisible(False)
            self.param_layout.itemAt(i * 2).widget().setVisible(False)
        
        # 根据选择的查询方式显示相应的输入框
        if button == self.query_by_dormitory_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(0).widget().setVisible(True)  # 宿舍ID标签
            self.param_layout.itemAt(1).widget().setVisible(True)  # 宿舍ID输入框
        elif button == self.query_by_status_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(2).widget().setVisible(True)  # 状态标签
            self.param_layout.itemAt(3).widget().setVisible(True)  # 状态下拉框
        else:
            self.param_group.setVisible(False)
    
    def perform_query(self):
        selected_option = self.query_button_group.checkedId()
        
        if selected_option == 1:  # 查询所有维修记录
            records = self.query.query_all_maintenance()
            self.display_results(records)
        
        elif selected_option == 2:  # 根据宿舍查询维修记录
            dormitory_id = self.dormitory_combo.currentData()
            
            if not dormitory_id:
                QMessageBox.warning(self, '警告', '请选择宿舍')
                return
            
            try:
                records, dormitory_name = self.query.query_maintenance_by_dormitory(dormitory_id)
                
                if records:
                    self.display_results(records)
                else:
                    self.result_table.setRowCount(0)
                    dorm_text = self.dormitory_combo.currentText()
                    QMessageBox.information(self, '提示', f'没有找到宿舍 {dorm_text} 的维修记录')
            except Exception as e:
                QMessageBox.warning(self, '警告', f'查询出错: {str(e)}')
        
        elif selected_option == 3:  # 根据维修状态查询记录
            status = self.status_combo.currentData()
            records = self.query.query_maintenance_by_status(status)
            
            if records:
                self.display_results(records)
            else:
                self.result_table.setRowCount(0)
                status_display = "待处理" if status == 'pending' else "处理中" if status == 'in_progress' else "已完成"
                QMessageBox.information(self, '提示', f'没有找到状态为 {status_display} 的维修记录')
    
    def display_results(self, records):
        if not records:
            self.result_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何维修记录')
            return
        
        self.result_table.setRowCount(len(records))
        
        for row, record in enumerate(records):
            self.result_table.setItem(row, 0, QTableWidgetItem(str(record[0])))
            self.result_table.setItem(row, 1, QTableWidgetItem(f"{record[1]}-{record[2]}"))
            self.result_table.setItem(row, 2, QTableWidgetItem(record[3]))
            self.result_table.setItem(row, 3, QTableWidgetItem(record[4]))
            
            status_display = "待处理" if record[5] == 'pending' else "处理中" if record[5] == 'in_progress' else "已完成"
            self.result_table.setItem(row, 4, QTableWidgetItem(status_display))
            
            resolved_date = record[6] if record[6] else "未解决"
            self.result_table.setItem(row, 5, QTableWidgetItem(resolved_date))

# 维修状态更新窗口
class UpdateMaintenanceWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.updater = MaintenanceUpdater()
        self.query = MaintenanceQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询所有维修记录
        self.refresh_btn = QPushButton('刷新维修记录')
        self.refresh_btn.clicked.connect(self.refresh_maintenance_list)
        layout.addWidget(self.refresh_btn)
        
        # 维修记录列表
        self.maintenance_table = QTableWidget()
        self.maintenance_table.setColumnCount(6)
        self.maintenance_table.setHorizontalHeaderLabels(['记录ID', '宿舍', '问题描述', '报修时间', '状态', '解决时间'])
        self.maintenance_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.maintenance_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.maintenance_table.itemSelectionChanged.connect(self.on_selection_changed)
        layout.addWidget(self.maintenance_table)
        
        # 更新表单
        self.update_group = QGroupBox('更新维修状态')
        update_layout = QFormLayout()
        
        self.status_combo = QComboBox()
        self.status_combo.addItem('待处理', 'pending')
        self.status_combo.addItem('处理中', 'in_progress')
        self.status_combo.addItem('已完成', 'completed')
        update_layout.addRow('新状态:', self.status_combo)
        
        self.update_group.setLayout(update_layout)
        layout.addWidget(self.update_group)
        
        # 更新按钮
        self.update_btn = QPushButton('更新维修状态')
        self.update_btn.clicked.connect(self.update_maintenance)
        self.update_btn.setEnabled(False)
        layout.addWidget(self.update_btn)
        
        self.setLayout(layout)
        
        # 初始加载维修记录列表
        self.refresh_maintenance_list()
    
    def refresh_maintenance_list(self):
        records = self.query.query_all_maintenance()
        
        if not records:
            self.maintenance_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何维修记录')
            return
        
        self.maintenance_table.setRowCount(len(records))
        
        for row, record in enumerate(records):
            self.maintenance_table.setItem(row, 0, QTableWidgetItem(str(record[0])))
            self.maintenance_table.setItem(row, 1, QTableWidgetItem(f"{record[1]}-{record[2]}"))
            self.maintenance_table.setItem(row, 2, QTableWidgetItem(record[3]))
            self.maintenance_table.setItem(row, 3, QTableWidgetItem(record[4]))
            
            status_display = "待处理" if record[5] == 'pending' else "处理中" if record[5] == 'in_progress' else "已完成"
            self.maintenance_table.setItem(row, 4, QTableWidgetItem(status_display))
            
            resolved_date = record[6] if record[6] else "未解决"
            self.maintenance_table.setItem(row, 5, QTableWidgetItem(resolved_date))
    
    def on_selection_changed(self):
        selected_rows = self.maintenance_table.selectionModel().selectedRows()
        self.update_btn.setEnabled(len(selected_rows) > 0)
        
        if len(selected_rows) > 0:
            row = selected_rows[0].row()
            status = self.maintenance_table.item(row, 4).text()
            if status == "待处理":
                self.status_combo.setCurrentIndex(0)
            elif status == "处理中":
                self.status_combo.setCurrentIndex(1)
            else:
                self.status_combo.setCurrentIndex(2)
    
    def update_maintenance(self):
        selected_rows = self.maintenance_table.selectionModel().selectedRows()
        
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要更新的维修记录')
            return
        
        row = selected_rows[0].row()
        maintenance_id = int(self.maintenance_table.item(row, 0).text())
        dormitory_name = self.maintenance_table.item(row, 1).text()
        current_status = self.maintenance_table.item(row, 4).text()
        new_status = self.status_combo.currentData()
        
        if (current_status == "待处理" and new_status == "pending") or \
           (current_status == "处理中" and new_status == "in_progress") or \
           (current_status == "已完成" and new_status == "completed"):
            QMessageBox.information(self, '提示', '维修状态未发生变化')
            return
        
        reply = QMessageBox.question(self, '确认更新', 
                                    f'确定要将宿舍 {dormitory_name} 的维修状态从 {current_status} 更新为 {self.status_combo.currentText()} 吗？',
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            result = self.updater.update_maintenance_status(maintenance_id, new_status)
            
            if result:
                QMessageBox.information(self, '成功', '维修状态已更新')
                self.refresh_maintenance_list()

# 宿舍维护管理主窗口
class MaintenanceManagementWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('宿舍维护管理')
        self.setGeometry(100, 100, 800, 600)
        self.initUI()
        
    def initUI(self):
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡窗口
        tab_widget = QTabWidget()
        
        # 创建宿舍维护管理的各个功能选项卡
        self.report_tab = QWidget()
        self.query_tab = QueryMaintenanceWidget()
        self.update_tab = UpdateMaintenanceWidget()
        
        # 设置报修宿舍选项卡
        report_layout = QVBoxLayout()
        report_btn = QPushButton('报修宿舍')
        report_btn.setMinimumHeight(50)
        report_btn.setFont(QFont('Arial', 12))
        report_btn.clicked.connect(self.open_report_dialog)
        report_layout.addWidget(report_btn)
        report_layout.addStretch()
        self.report_tab.setLayout(report_layout)
        
        # 添加选项卡
        tab_widget.addTab(self.report_tab, '报修宿舍')
        tab_widget.addTab(self.query_tab, '维修记录查询')
        tab_widget.addTab(self.update_tab, '维修状态更新')
        
        main_layout.addWidget(tab_widget)
        
        # 返回按钮
        back_btn = QPushButton('返回主菜单')
        back_btn.clicked.connect(self.close)
        main_layout.addWidget(back_btn)
    
    def open_report_dialog(self):
        dialog = ReportMaintenanceDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果报修成功，刷新查询和更新选项卡的数据
            self.query_tab.perform_query()
            self.update_tab.refresh_maintenance_list()

# 如果直接运行此文件，提供测试界面
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MaintenanceManagementWindow()
    window.show()
    sys.exit(app.exec_())